package com.jinjiafeng.baselibrary.permission;

import android.support.v4.app.ActivityCompat;

import java.util.List;

/**
 * @author jinjiafeng
 * Data：18-5-24-下午2:10
 * Description:
 */
public class PermissionHelper {

    private final Object mObj;
    private int mRequestCode;
    private String[] mPermissions;

    private PermissionHelper(Object obj) {
        this.mObj = obj;
    }

    public static void requestPermission(Object obj, int requestCode, String... permission) {
        PermissionHelper.with(obj).requestCode(requestCode).requestPermission(permission).request();
    }


    public void request() {
        if (!PermissionUtils.isOverMarshmallow()) {
            PermissionUtils.executeSucceedMethod(mObj, mRequestCode);
        } else {
            final List<String> deniedList = PermissionUtils.getDeniedPermission(mObj, mPermissions);
            if (deniedList.size() == 0) {
                PermissionUtils.executeSucceedMethod(mObj, mRequestCode);
            } else {
                ActivityCompat.requestPermissions(PermissionUtils.getActivity(mObj), mPermissions, mRequestCode);
            }
        }
    }

    public PermissionHelper requestPermission(String... permissions) {
        this.mPermissions = permissions;
        return this;
    }

    public PermissionHelper requestCode(int requestCode) {
        this.mRequestCode = requestCode;
        return this;
    }

    public static PermissionHelper with(Object obj) {
        return new PermissionHelper(obj);
    }

    public static void requestPermissionsResult(Object obj, int requestCode, String[] permissions) {
        final List<String> deniedList = PermissionUtils.getDeniedPermission(obj, permissions);
        if(deniedList.size() == 0){
            // 权限用户都同意授予了
            PermissionUtils.executeSucceedMethod(obj,requestCode);
        }else{
            // 你申请的权限中 有用户不同意的
            PermissionUtils.executeFailedMethod(obj,requestCode);
        }
    }
}
